package org.jaaksi.kottlindemo.test

import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.doOnEnd
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_test_cou.*
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.jaaksi.kottlindemo.databinding.FragmentTestanimBinding
import org.jaaksi.kottlindemo.ui.SecondActivity
import org.jetbrains.anko.startActivity
import timber.log.Timber
import java.util.*
import kotlin.concurrent.thread

class TestAnimFragment2 : Fragment() {
    private lateinit var binding: FragmentTestanimBinding
    private var anim: ValueAnimator? = null

    @SuppressLint("HandlerLeak")
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            println(">> handleMessage getView = $view, isAdded = $isAdded, getHost = $host") // 都为false，判断一下isAdded
            viewLifecycleOwner
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
//        println("savedInstanceState = $savedInstanceState $this")
        binding = FragmentTestanimBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.btnStart.setOnClickListener {

//            requireActivity().startActivity<SecondActivity>()
        }


        binding.btnNext.setOnClickListener {
            for (i in 1..10) {
                refresh()
            }

        }
    }

    private var num = 0

    //    线程中锁都是阻塞式，在没有获取锁时无法执行其他逻辑，而协程可以通过挂起函数解决这个，
//    没有获取锁就挂起协程，获取后再恢复协程，协程挂起时线程并没有阻塞可以执行其他逻辑。
//    这种互斥锁就是Mutex，它与synchronized关键字有些类似，还提供了withLock扩展函数，
//    替代常用的mutex.lock; try {...} finally { mutex.unlock() }:
    private val mutex = Mutex()

    private fun refresh() {
        GlobalScope.launch {
            mutex.withLock {
                delay(500)
                num++
                withContext(Dispatchers.Main) {
                    Timber.e(">> $num")
                }

            }

        }
    }

    private fun test1() {
        handler.sendEmptyMessageDelayed(0, 1000)
        requireActivity().startActivity<SecondActivity>()

        anim = ValueAnimator.ofFloat(0f, 100f).apply {
            duration = 1000
            doOnEnd {
                if (!isAdded) return@doOnEnd
                viewLifecycleOwner
            }
            addUpdateListener {
                println(">> update")
                // fixme 没有cancel的动画或者handle必须在响应的时候判断isAdded。为了安全起见，建议在动画的update和end以及handle中添加判断
                if (!isAdded) return@addUpdateListener
                viewLifecycleOwner
            }
            start()
        }

//            binding.btnNext.postDelayed({
//                viewLifecycleOwner
//            },1000)
        lifecycleScope.launch {
            // fixme 使用lifecycleScope做延迟，在声明周期结束后，后面的代码不会被执行
            println(">> lifecycleScope launch start")
            delay(200)
            println(">> lifecycleScope delay 200")
            println(">> $viewLifecycleOwner")
            delay(1000)
            // 延迟1s后，fragment已销毁，下面的代码无法执行
            println(">> lifecycleScope delay 300")
            println(">> $viewLifecycleOwner")
        }
    }


    override fun onDestroyView() {
        println(">> onDestroyView")
        super.onDestroyView()
        anim?.cancel()
        handler.removeCallbacksAndMessages(null)
    }
}